<?php
require 'TVB/pms/pdes/common/bootstrap.php';
require 'TVB/pms/pdes/common/util/UpdateMeta.class.php';
require 'TVB/ImageInfrastructure/Client/requires.php';
require 'TVB/VideoInfrastructure/Client/requires.php';
require_once 'TVB/pms/pdes/common/util/ChangeLogTools.class.php';

empty($_REQUEST['action']) && blue_error(2,'action is null');

// common functions
function blue_error($errno,$msg=array()){/*{{{*/
	if(!is_array($msg)) $msg = array($msg);
    $array =array(
        'status'=>'-1',
        'message'=>$msg,
    );
    switch($errno){
    case 1: array_unshift($array['message'] , 'Data Error'); break;
    case 2: array_unshift($array['message'] , 'Parameters Error'); break;
    case 3: array_unshift($array['message'] , 'Network Error'); break;
    case 4: array_unshift($array['message'] , 'Error'); break;
    }
    exit(json_encode($array));
}
function blue_data($data){
    exit(json_encode(array('status'=>1,'data'=>$data)));
}
function _get_programme_id($type,$id){
	if(!in_array($type,array('Programme','Episode','Cast'))) blue_error(2,'type error');
	switch($type){
	case 'Programme':
		return $id;
	break;
	case 'Episode':
		$obj = new episode();
		$obj = $obj->get($id);
		return $obj->programme_id;
	break;
	case 'Cast':
		$obj = new cast();
		$obj = $obj->get($id);
		return $obj->programme_id;
	break;
	}
}/*}}}*/

// Action
$func_name = $_REQUEST['action'];/*{{{*/
switch ($_REQUEST['action'])
{
case 'upload';
    !isset($_REQUEST['id']) ?             blue_error(2,'id is null') :              $id = $_REQUEST['id']+0;
    !isset($_REQUEST['folder']) ?         blue_error(2,'folder is null') :          $folderid = $_REQUEST['folder']+0;
    !isset($_REQUEST['folder_type']) ?    blue_error(2,'folder_type is null') :     $folder_type = $_REQUEST['folder_type']+0;
	!isset($_REQUEST['type']) ?		      blue_error(2,'type is null') :		    $caller_type = $_REQUEST['type'];
	!isset($_REQUEST['user_id']) ?		  blue_error(2,'user_id is null') :		    $user_id = $_REQUEST['user_id'];

	
	if(AC::FOLDER_TYPE_VIDEO == $folder_type){
		if(empty($_REQUEST['video'])){
			blue_error(2,'video is null');
		}else{
			$video = json_decode($_REQUEST['video'],true);
		}
	}else $video = array();

	$null_da = array(
		'permission' => array('country_allow_list'=>'','country_deny_list'=>'','time_online'=>'','time_offline'=>''),
		'metadata'  => array('title'=>'','tag'=>'','person'=>'','miscellaneous'=>''),
		'basicinfo' => array('title'=>'','tag'=>'','desc'=>''),
	);

	$caller_type = ucfirst(strtolower(trim($caller_type)));
	$objdata = empty($_REQUEST['objdata'])? $null_da : json_decode($_REQUEST['objdata'],true);

    $func_name($folderid, $id, $folder_type, $caller_type, $objdata, $video, $user_id);
break;
case 'get_country':
	$func_name();
break;
case 'get_system_tags':
    !isset($_REQUEST['id']) ?             blue_error(2,'id is null') :              $id = $_REQUEST['id']+0;
    !isset($_REQUEST['folder_type']) ?    blue_error(2,'folder_type is null') :     $folder_type = $_REQUEST['folder_type']+0;
    !isset($_REQUEST['type']) ?		      blue_error(2,'type is null') :		    $caller_type = $_REQUEST['type'];
	$caller_type = ucfirst(strtolower(trim($caller_type)));
	$func_name($caller_type,$folder_type,$id);
break;
case 'get_video_id':
	$func_name();
break;
case 'all_right':
    !isset($_REQUEST['id']) ?             blue_error(2,'id is null') :              $id = $_REQUEST['id']+0;
	!isset($_REQUEST['type']) ?		      blue_error(2,'type is null') :		    $caller_type = $_REQUEST['type'];
    !isset($_REQUEST['video_id']) ?       blue_error(2,'video_id is null') :        $video_id = $_REQUEST['video_id'];
    !isset($_REQUEST['folder']) ?         blue_error(2,'folder is null') :          $folderid = $_REQUEST['folder']+0;
	$caller_type = ucfirst(strtolower(trim($caller_type)));
	$func_name($folderid, $caller_type,$id,$video_id);
break;
case 'check_episode_no':
    !isset($_REQUEST['id']) ?             blue_error(2,'id is null') :              $id = $_REQUEST['id']+0;
	!isset($_REQUEST['type']) ?		      blue_error(2,'type is null') :		    $caller_type = $_REQUEST['type'];
    !isset($_REQUEST['episode_no']) ?     blue_error(2,'on air episode no is null'):$episode_no = $_REQUEST['episode_no'];
	$caller_type = ucfirst(strtolower(trim($caller_type)));
	$func_name($caller_type,$id,$episode_no);
break;
}/*}}}*/

// check 'on air episode no'
function check_episode_no($caller_type, $id, $episode_no){
	$programme_id = _get_programme_id($caller_type,$id);
	$episode_id   = episode::getEpisodeID($programme_id,$episode_no);
	if($episode_id){
		blue_data(1);
	}else{
		blue_error(4,"'On Air Episode No' not exists!");
	}
}

// upload 
function upload($folderid, $id, $folder_type, $caller_type, $objdata, $video, $uploader)/*{{{*/
{
	if(UPLOAD_ERR_OK != $_FILES['Filedata']['error']) blue_error(1,'no file');

	$resource = $_FILES['Filedata']['tmp_name'];
	$src_name = $_FILES['Filedata']['name'];
	$do_point = strrpos($src_name, '.');
	$ext_name = substr( $src_name, $do_point);
	$the_name = substr( $src_name, 0, $do_point);
	
	// 手動指定出世紙信息
	$tag = get_system_tags($caller_type, $folder_type, $id,true);

	$objdata['basicinfo'] = array('title'=>$the_name,'tag'=>$tag,'desc'  =>''); 
	#$objdata['basicinfo'] = array('title'=>$the_name,'tag'=>$tag,'desc'  =>$src_name); 
	$objdata['metadata']  = array('title'=>$the_name,'tag'=>$tag,'person'=>$uploader, 'miscellaneous'=>array()); 


	if( AC::FOLDER_TYPE_IMAGE == $folder_type )
	{
		Model::$dbo['w']->beginTransaction();
		try{
			_upload_image($folderid, $uploader,$id,$caller_type,$resource,$src_name,$objdata['permission'],$objdata['basicinfo']);
			Model::$dbo['w']->commit();
		}catch(Exception $e){
			error_log('Blue->Function "upload[image]" Error Message:'.$e);
			error_log('Blue->Function "upload[image]" Parameters:'.print_r(func_get_args(),1));
			Model::$dbo['w']->rollBack();
			blue_error(1,'system error!');
		}
	}
	else if( AC::FOLDER_TYPE_VIDEO == $folder_type )/*{{{*/
	{
		$video_id  = $video['video_id'];

		$video_dir = AC::VIDEO_STORE_PATH . $video_id . '/'; 
		$part_dir  = $video_dir . 'part/';

		file_exists($part_dir) || mkdir($part_dir,0755,true);

		if($video['is_image'])
		{

			$image_info = getimagesize($resource);
			if(!$image_info){
				blue_error(2,"$source_file not is image file");
			}
			move_uploaded_file($resource, $part_dir.'image'.$ext_name);
		}
		else if(strpos(','.AC::VIDEO_UPLOAD_TYPES.',',",$ext_name,")!==false)
		{
			$video_info = CommonUtils::GetVideoInformation($resource);
			if(
				empty($video_info['General']['Format'])
				|| $video_info['General']['Format']!='MPEG-4'
				|| mime_content_type($resource) != 'video/mp4'
			){
				blue_error(2,'not a MPGE-4 file');
			}

			move_uploaded_file($resource, $part_dir.sprintf("%012d",$video['file_index']).$ext_name);

			if(!file_exists($video_dir.'uploading')){
				file_put_contents($video_dir.'uploading',json_encode(
					array(
						'basicinfo' => $objdata['basicinfo'],
						'metadata'  => $objdata['metadata'],
						'dispsize'  => $video_info['Video']['DisplayAspectRatio/String']
					)
				));
			}
		}
		else
		{
			blue_error(2,'not is vidoe file');
		}

		// vidoe: upload to pdes server
		// video: append job to cornjob listing
	}/*}}}*/
	blue_data(1);
}/*}}}*/

// for all video part was uploaded
function all_right($folderid,$caller_type,$id,$video_id){/*{{{*/
	$programme_id = _get_programme_id($caller_type,$id);
	$video_dir    = AC::VIDEO_STORE_PATH . $video_id . '/';
	$deflang      = language::getLanguageID(AC::DEFAULT_LANGUAGE);

	$objdata      = json_decode(file_get_contents($video_dir.'uploading'),true);

	$uploader     = CommonUtils::get_user();
	$now_time     = date('Y-m-d H:i:s');
	$video_obj    = new video();

	$export_list = array();
	
	if($objdata['dispsize'] == '16/9'){
		$export_list[] = 'mp4_hq';
		$export_list[] = 'mp4_mq';
		$export_list[] = 'mp4_lq';
	} else {
		$export_list[] = 'mp4_4/3:hq';
		$export_list[] = 'mp4_4/3:mq';
		$export_list[] = 'mp4_4/3:lq';
	}
	
	$f = new folder();
	$folder = $f->get($folderid);
	if (is_object($folder) && $folder->folder_type_id != 20)  { // 20 - catchup type id
		if ($objdata['dispsize'] == '16/9') {
			$export_list[] =  '3gp_mq';
            //$export_list[] =  'iphone_mp4_mq';
            //$export_list[] =  'iphone_mp4_lq';
		} else {
			$export_list[] =  '3gp_4/3:mq';
            //$export_list[] =  'iphone_mp4_4/3:mq';
            //$export_list[] =  'iphone_mp4_4/3:lq';
		}
	}
	
	$exports = implode(",", $export_list);

	Model::$dbo['w']->beginTransaction();

	if(isset($_REQUEST['act']) && $_REQUEST['act']=='update'){
		try{
			$video_obj = Model::$dbo['w']->find('video','id=?',array($video_id));
			$video_obj = $video_obj[0];
			$video_obj->ii_id               = '';
			$video_obj->ii_status           = AC::IMAGE_STATUS_WAITING;
			$video_obj->thumbnail_url       = '';
			$video_obj->image_source_url    = '';

			$video_obj->vi_id               = '';
			$video_obj->vi_status           = AC::VIDEO_STATUS_QUEUE;
			$video_obj->video_params        = '';
			$video_obj->source_url          = '';
			Model::$dbo['w']->save($video_obj);
			change_log::updateOne(array(
				'type'=>'video',
				'keys'=>array('id'=>$video_obj->id),
				'is_active'=>1,
				'is_publish'=> 0,
				'programme_id'=>$programme_id
			));

			/* -----------begin    
			 * change the time of this video's chapter when the video is changed  
			 * #added by Albie Lu on 2011-11-07
			 * */

			//get the totle duration of the video
			$files = glob( $video_dir.'part/*.mp4');
			$video_duration=0;
			foreach ($files as $file){
				
				$video_info = CommonUtils::GetVideoInformation($file);
				$video_duration += floor($video_info['Video']['Duration']/1000);
			}

			/* if the in_time or out_time of chapter is greater than the video duration,
			 * set them to the video duration.*/
			$sql = "select id,in_time,out_time from chapter where video_id='{$video_id}' and status=".AC::STATUS_NEW." and (in_time>'{$video_duration}' or out_time>'{$video_duration}')";
			$chapter_lists = Model::$dbo['r']->findBySql('chapter', $sql);	
			foreach ($chapter_lists as $chapter_one){
				$chapter_one->in_time = ($chapter_one->in_time > $video_duration) ? $video_duration : $chapter_one->in_time;
				$chapter_one->out_time = $video_duration;
				$chapter_one->modified_at = $now_time;
				$chapter_one->modified_by = $uploader;
				Model::$dbo['w']->save($chapter_one);
				//change_log
				change_log::updateOne(array(
					'type'=>'chapter',
					'keys'=>array('id'=>$chapter_one->id),
					'is_active'=>1,
					'is_publish'=> 0,
					'programme_id'=>$programme_id
				));
			}

			//if the max out_time of chapter < video duration,set this out_time to video duration  
			if(count($chapter_lists)==0){
				$sql_c = "select max(in_time) from chapter where video_id='{$video_id}' and status=".AC::STATUS_NEW;
				$sql = "select id,in_time,out_time from chapter where video_id='{$video_id}' and status=".AC::STATUS_NEW." and in_time=(".$sql_c.")";
				$chapter_lists = Model::$dbo['r']->findBySql('chapter', $sql);
				$n=0;
				foreach($chapter_lists as $chapter_one){
					if( $chapter_one->out_time<$video_duration ){
						if($n<0){
							$chapter_one->in_time = $video_duration;
						}
						$n--;
						$chapter_one ->out_time = $video_duration;
						$chapter_one->modified_at = $now_time;
						$chapter_one->modified_by = $uploader;
						Model::$dbo['w']->save($chapter_one);
						//change_log
						change_log::updateOne(array(
							'type'=>'chapter',
							'keys'=>array('id'=>$chapter_one->id),
							'is_active'=>1,
							'is_publish'=> 0,
							'programme_id'=>$programme_id
						));
					}
				}
			}
			//------------end

			/*
			$vol = Model::$dbo['w']->find('video_language','video_id=? and language_id=?',array($video_id,$deflang));
			$vol = $vol[0];
			$vol->title       = empty($objdata['basicinfo']['title']   ) ? '' : $objdata['basicinfo']['title'];   
			$vol->description = empty($objdata['basicinfo']['desc']    ) ? '' : $objdata['basicinfo']['desc'];    
			$vol_id = Model::$dbo['w']->save_by_fields($vol,array('video_id','language_id'));
			*/
			Model::$dbo['w']->commit();
		}catch(Exception $e){
			error_log('Blue->Function "all_right" Error Message:'.$e);
			error_log('Blue->Function "all_right" Parameters:'.print_r(func_get_args(),1));
			Model::$dbo['w']->rollBack();
		}

		$objdata = array('video_id' => $video_id, 'metadata'=>$objdata['metadata'],'exports'=>$exports);
		file_put_contents($video_dir.'uploading',json_encode($objdata));
		rename( $video_dir . 'uploading' , $video_dir . 'finished');
		blue_data(1);
	}

	try{
		$all_data   = json_decode($_REQUEST['objdata'],1);
		$permission_data = $all_data['permission'];

		# change_log
		$change_logs = array();

        $programme = new programme;
        $programme_detail = $programme->get($programme_id);
        if ($programme_detail->premium_flag) {
            $video_obj->premium_flag = 1;
        }

		$video_obj->programme_id        = $programme_id;

		$video_obj->ii_id               = '';
		$video_obj->ii_status           = AC::IMAGE_STATUS_WAITING;
		$video_obj->thumbnail_url       = '';
		$video_obj->image_source_url    = '';

		$video_obj->vi_id               = '';
		$video_obj->vi_status           = AC::VIDEO_STATUS_QUEUE;
		$video_obj->source_url          = '';
		$video_obj->other_videos        = '';
		$video_obj->first_time_onair    = '';
		$video_obj->highlighted_cast_roles= '';
		$video_obj->available_tag_types = '';
		$video_obj->casts               = '';
		$video_obj->tags                = '';
		$video_obj->folders             = '';
		$video_obj->country_allow_list  = strtoupper($permission_data['country_allow_list']);
		$video_obj->country_deny_list   = strtoupper($permission_data['country_deny_list']);
		$video_obj->publish_datetime    = date('Y-m-d H:i',strtotime($permission_data['time_online']));
		$video_obj->expire_datetime     = date('Y-m-d H:i',strtotime($permission_data['time_offline']));
		$video_obj->copyright           = '';
		$video_obj->status              = AC::STATUS_NEW;
		$video_obj->mdes_status         = AC::STATUS_NEW;
		$video_obj->created_at          = $now_time;
		$video_obj->created_by          = $uploader;
		$video_obj->modified_at         = $now_time;
		$video_obj->modified_by         = $uploader;
		$vo_id = Model::$dbo['w']->save($video_obj);
		$change_logs[] = array(
			'type'=>'video',
			'keys'=>array('id'=>$vo_id),
			'is_active'=>1,
			'is_publish'=> 0,
			'programme_id'=>$programme_id
		);

		//create video log
		$vo_log = new audit_log();
		$vo_log->item_type_id = item_type::getItemIDByName('video');
		$vo_log->item_id = $vo_id;
		$vo_log->modified_at = date("Y-m-d H:i:s");
		$vo_log->modified_by = $uploader;
		$vo_log->status  = AC::STATUS_NEW;
		$vo_log->remarks = ($vo_id > 0) ? "create video success" : " create video failed";
		$vo_log->action  = AC::LOG_OP_CREATE;
		$vo_log->data    = json_encode($video_obj);
		Model::$dbo['w']->save($vo_log);

		$vol = new video_language();
		$vol->video_id    = $vo_id;
		$vol->language_id = $deflang;
		$vol->title       = empty($objdata['basicinfo']['title']   ) ? '' : $objdata['basicinfo']['title'];   
		//$vol->description = '';    
		$vol->description = empty($objdata['basicinfo']['desc']    ) ? '' : $objdata['basicinfo']['desc'];    
		$vol_id = Model::$dbo['w']->save($vol);
		$change_logs[] = array(
			'type'=>'video-language',
			'keys'=>array('video_id'=>$vo_id,'language_id'=>$deflang),
			'is_active'=>1,
			'is_publish'=> 0,
			'programme_id'=>$programme_id
		);

		//create video log
		$vol_log = new audit_log();
		$vol_log->item_type_id = item_type::getItemIDByName('video-language');
		$vol_log->item_id = $vo_id;
		$vol_log->modified_at = date("Y-m-d H:i:s");
		$vol_log->modified_by = $uploader;
		$vol_log->status  = AC::STATUS_NEW;
		$vol_log->remarks = ($vol_id > 0) ? "create video language success" : "create video language failed";
		$vol_log->action  = AC::LOG_OP_CREATE;
		$vol_log->data    = json_encode($vol);
		Model::$dbo['w']->save($vol_log);

		if('Episode' == $caller_type || isset($all_data['episodeNo'])){
			if(isset($all_data['episodeNo'])){
				$episode_id = episode::getEpisodeID($programme_id,$all_data['episodeNo']);
			}else{
				$episode_id = $id;
			}
			$sql = 'INSERT INTO `episode-video`(`episode_id`,`video_id`) VALUES(:a,:b)';
			Model::updateBySql($sql,array(':a'=>$episode_id,':b'=>$vo_id));
			$change_logs[] = array(
				'type'=>'episode-video',
				'keys'=>array('video_id'=>$vo_id,'episode_id'=>$episode_id),
				'is_active'=>1,
				'is_publish'=> 0,
				'programme_id'=>$programme_id,
			);
		}

		$folder_item_obj = new folder_item();
		$max_rank = $folder_item_obj->getMaxRank($folderid);
		Model::updateBySql('insert into folder_item values(:fid,:item_id,:rank)',array(':fid'=>$folderid,':item_id'=>$vo_id,':rank'=>$max_rank+1));
		Model::updateBySql('insert into `folder_item-language` values(:fid,:item_id,:lang,:title,:desc)',array(':fid'=>$folderid,':item_id'=>$vo_id,':lang'=>$deflang,':title'=>$vol->title,':desc'=>$vol->description));
		$change_logs[] = array(
			'type'=>'folder',
			'keys'=>array('id'=>$folderid),
			'is_active'=>1,
			'is_publish'=> 0,
			'programme_id'=>$programme_id,
		);
		$change_logs[] = array(
			'type'=>'folder_item',
			'keys'=>array('folder_id'=>$folderid,'item_id'=>$vo_id),
			'is_active'=>1,
			'is_publish'=> 0,
			'programme_id'=>$programme_id,
		);
		$change_logs[] = array(
			'type'=>'folder_item-language',
			'keys'=>array('folder_id'=>$folderid,'item_id'=>$vo_id,'language_id'=>$deflang),
			'is_active'=>1,
			'is_publish'=> 0,
			'programme_id'=>$programme_id,
		);

		# insert premium tables
		$premium_static = array('ppv'=>0,'subscription'=>0);
		if(isset($permission_data['ppvStartTime']) && isset($permission_data['ppvEndTime'])){
			Model::updateBySql(
				'insert into video_ppv(video_id,country_allow_list,country_deny_list,publish_datetime,expire_datetime)values(?,?,?,?,?)',
				array(
					$vo_id,
					AC::DEFAULT_COUNTRY_ALLOW_LIST,
					AC::DEFAULT_COUNTRY_DENY_LIST,
					date('Y-m-d H:i',strtotime($permission_data['ppvStartTime'])),
					date('Y-m-d H:i',strtotime($permission_data['ppvEndTime']))
				)
			);
			$premium_static['ppv'] = 1;	
			$change_logs[] = array(
				'type'=>'video_ppv',
				'keys'=>array('video_id'=>$vo_id),
				'is_active'=>1,
				'is_publish'=> 0,
				'programme_id'=>$programme_id,
			);
		}
		if(isset($permission_data['subscriptionStartTime']) && isset($permission_data['subscriptionEndTime'])){
			Model::updateBySql(
				'insert into video_subscription(video_id,country_allow_list,country_deny_list,publish_datetime,expire_datetime)values(?,?,?,?,?)',
				array(
					$vo_id,
					AC::DEFAULT_COUNTRY_ALLOW_LIST,
					AC::DEFAULT_COUNTRY_DENY_LIST,
					date('Y-m-d H:i',strtotime($permission_data['subscriptionStartTime'])),
					date('Y-m-d H:i',strtotime($permission_data['subscriptionEndTime']))
				)
			);
			$premium_static['subscription'] = 1;	
			$change_logs[] = array(
				'type'=>'video_subscription',
				'keys'=>array('video_id'=>$vo_id),
				'is_active'=>1,
				'is_publish'=> 0,
				'programme_id'=>$programme_id,
			);
		}
		if(array_sum($premium_static)){
			Model::updateBySql(
				'insert into video_premium(video_id,ppv_flag,subscription_flag)values(?,?,?)',
				array($vo_id,$premium_static['ppv'],$premium_static['subscription'])
			);
			$change_logs[] = array(
				'type'=>'video_premium',
				'keys'=>array('video_id'=>$vo_id),
				'is_active'=>1,
				'is_publish'=> 0,
				'programme_id'=>$programme_id,
			);

            // for bug 6708
			$video = Model::$dbo['w']->find('video','id=?',array($vo_id));
            $video = $video[0];
            $video->premium_flag = 1;
		    Model::$dbo['w']->save($video);
		}
		array_walk($change_logs,'change_log::updateOne');

		#$meta_obj = new UpdateMeta('Video',$vo_id);
		#$meta_obj->UpdateAcl();  // no vi.source_id, so need update acl

		Model::$dbo['w']->commit();

	}catch(Exception $e){
		error_log('Blue->Function "all_right" Error Message:'.$e);
		error_log('Blue->Function "all_right" Parameters:'.print_r(func_get_args(),1));
		Model::$dbo['w']->rollBack();
		blue_error(1,'system error!');
	}

	$objdata = array('video_id' => $vo_id, 'metadata'=>$objdata['metadata'],'exports'=>$exports);
	file_put_contents($video_dir.'uploading',json_encode($objdata));
	rename( $video_dir . 'uploading' , $video_dir . 'finished');

	blue_data(1);
}/*}}}*/

// get country list
function get_country(){/*{{{*/
	$rs = parseCountryCode::parseXml(AC::COUNTRY_LIST_CODE, true);
	$cs = array();
	foreach($rs as $region_name => $zones){
		foreach($zones as $zone_name => $countries){
			foreach($countries as $country_name => $country){
				if(empty($country[1])){
					$cs[] = array('id'=>$country_name,'name'=>$country[0]);
				}
			}
		}
	}
	usort($cs,function($a,$b){ return strcmp($a['name'], $b['name']); });
	blue_data($cs);
}/*}}}*/

// get caller(Programme|Episode|Cast) system_tags 
function get_system_tags($caller_type, $folder_type, $id,$get=false){/*{{{*/
	if(AC::FOLDER_TYPE_IMAGE == $folder_type){
		$meta_obj = new UpdateMeta('Image');
	}else if(AC::FOLDER_TYPE_VIDEO == $folder_type){
		$meta_obj = new UpdateMeta('Image');
		//$meta_obj = new UpdateMeta('Video',$id);
	}

	$meta_obj->getSystemTags();

	if('Programme' == $caller_type){
		$id = _get_programme_id($caller_type,$id);
	}

	$system_tags = call_user_func_array(array($meta_obj,'UpdateMeta'.$caller_type),array($id));
	$system_tagstr = implode(' ',array_values($system_tags));
	if($get){
		return $system_tagstr;
	}
	blue_data($system_tagstr);
}/*}}}*/

// get temporary video id
function get_video_id(){/*{{{*/
	blue_data(uniqid());
}/*}}}*/

// upload image
function _upload_image($folderid, $uploader,$id,$caller_type,$file,$file_name,$permission,$basicinfo=null){/*{{{*/
	$programme_id = _get_programme_id($caller_type,$id);
    $deflang      = language::getLanguageID(AC::DEFAULT_LANGUAGE);
	$now_time     = date('Y-m-d H:i:s');

	if('Episode' == $caller_type) $episode_id = $id;
	else $episode_id = 0;

	// insert image to db ============
	$io = new image();
	$io->ii_id             = 0 ;  //$ii_id;
	$io->thumbnail_url	   = '';  //$is->preview_url;
	$io->source_url        = '';  //$src_url;
	$io->programme_id      = $programme_id;
	$io->episode_id        = $episode_id;
	$io->original_filename = $file_name;
	$io->country_allow_list= strtoupper($permission['country_allow_list']);
	$io->country_deny_list = strtoupper($permission['country_deny_list']);
	$io->publish_datetime  = date('Y-m-d H:i',strtotime($permission['time_online']));
	$io->expire_datetime   = date('Y-m-d H:i',strtotime($permission['time_offline']));
	$io->copyright         = '';
	$io->status            = AC::STATUS_NEW;
	$io->mdes_status       = AC::STATUS_NEW;
	$io->modified_at       = $now_time;
	$io->created_at        = $now_time;
	$io->created_by        = $uploader;
	$io->modified_by       = $uploader;
	$io_id = Model::$dbo['w']->save($io);

	//create image log
	$io_log = new audit_log();
	$io_log->item_type_id = item_type::getItemIDByName('image');
	$io_log->item_id = $io_id;
	$io_log->modified_at = date("Y-m-d H:i:s");
	$io_log->modified_by = $uploader;
	$io_log->status  = AC::STATUS_NEW;
	$io_log->remarks = ($io_id > 0) ? "create image success" : " create image failed";
	$io_log->action  = AC::LOG_OP_CREATE;
	$io_log->data    = json_encode($io);
	Model::$dbo['w']->save($io_log);

	$iol = new image_language();
	$iol->image_id    = $io_id;
	$iol->language_id = $deflang;
	$iol->title       = empty($basicinfo['title']   ) ? '' : $basicinfo['title'];   
	$iol->description = empty($basicinfo['desc']    ) ? '' : $basicinfo['desc'];    
	$iol_id = Model::$dbo['w']->save($iol);

	//image language log
	$iol_log = new audit_log();
	$iol_log->item_type_id = item_type::getItemIDByName('image-language');
	$iol_log->item_id = $io_id;
	$iol_log->modified_at = date("Y-m-d H:i:s");
	$iol_log->modified_by = $uploader;
	$iol_log->status  = AC::STATUS_NEW;
	$iol_log->remarks = ($iol_id >= 0) ? "create image language success" : " create image language failed";
	$iol_log->action  = AC::LOG_OP_CREATE;
	$iol_log->data    = json_encode($iol);
	Model::$dbo['w']->save($iol_log);
	
	$folder_item_obj = new folder_item();
	$max_rank = $folder_item_obj->getMaxRank($folderid);
	Model::updateBySql('insert into folder_item values(:fid,:item_id,:rank)',array(':fid'=>$folderid,':item_id'=>$io_id,':rank'=>$max_rank+1));
	Model::updateBySql('insert into `folder_item-language` values(:fid,:item_id,:lang,:title,"")',array(':fid'=>$folderid,':item_id'=>$io_id,':lang'=>$deflang,':title'=>$file_name));
	

	// Watermark & Thumbnail ======  暫時不需要 Watermark & Thumbnail
	$upload_status = CommonUtils::upload_image_to_ii($file);
	
	// UpdateMeta ===================
	$meta_obj = new UpdateMeta('Image',$io_id);
	$meta_obj->UpdateAcl();
	$meta_obj->UpdateMetaProgramme(); //所有type必須的
	if('Programme' != $caller_type)   call_user_func_array(array($meta_obj,'UpdateMeta'.$caller_type),array($id));

	$uploaded = ( array_sum($upload_status['status']) == count($upload_status['status']) );
	if(!$uploaded) throw new Exception($upload_status['error_msg']);
	
	// Update image url ============
	$new_io = $io->get($io_id);
	$new_io->ii_id         = $upload_status['source_id'];
	$new_io->ii_status     = $upload_status['ii_status'];
	$new_io->source_url    = $upload_status['source_url'];
	$new_io->thumbnail_url = $upload_status['thumbnail_url'];
	Model::$dbo['w']->save($new_io);

	# change_log
	$change_logs  = array();
	switch($caller_type){
	case 'Programme':
		$change_data = array('programme_id'=>$id,'episode_id'=>array());
		break;
	case 'Episode':
		$change_data = array('programme_id'=>0,'episode_id'=>array($id));
		break;
	case 'Cast':
		$change_data = ChangeLogTools::getEpisodeIdsByCastId($id);
		break;
	}
	$change_data['is_active']  = 1;
	$change_data['is_publish'] = 0;
	$change_data['type'] = 'image';
	$change_data['keys'] = array('id'=>$io_id);
	$change_logs[] = $change_data;
	$change_data['type'] = 'image-language';
	$change_data['keys'] = array('image_id'=>$io_id,'language_id'=>$deflang);
	$change_logs[] = $change_data;
	$change_data['type'] = 'folder_item';
	$change_data['keys'] = array('folder_id'=>$folderid,'item_id'=>$io_id);
	$change_logs[] = $change_data;
	$change_data['type'] = 'folder_item-language';
	$change_data['keys'] = array('folder_id'=>$folderid,'item_id'=>$io_id,'language_id'=>$deflang);
	$change_logs[] = $change_data;
	array_walk($change_logs,'change_log::updateOne');

	return $io_id;
}/*}}}*/


